<template>
    <div class="app-container">

                <!-- 搜索区 -->
        <el-form :model="queryParam" ref="queryForm" size="small" :inline="true">

            <el-form-item label="商品名称" prop="name">
                <el-input v-model="queryParam.name" placeholder="请输入商品名称" clearable style="width: 240px"
                          @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="状态" prop="isgrounding">
              <el-select v-model="queryParam.isgrounding" placeholder="请选择" clearable>
                <el-option v-for="item in dicts.shop_background" :key="item.id" :label="item.dictLabel" :value="item.dictValue">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            </el-form-item>
        </el-form>


        <!--功能区-->
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                        type="primary"
                        plain
                        icon="el-icon-plus"
                        size="mini"
                        v-shop
                        @click="handleAdd()"
                >新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="success"
                        plain
                        icon="el-icon-edit"
                        size="mini"
                        v-shop
                        :disabled="single"
                        @click="handleUpdate()"
                >修改</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="danger"
                        plain
                        icon="el-icon-delete"
                        size="mini"
                        v-shop
                        :disabled="multiple"
                        @click="handleDown()"
                >批量下架</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button
                        type="warning"
                        plain
                        icon="el-icon-download"
                        size="mini"
                        @click="handleExcel()"
                >导出</el-button>
            </el-col>
        </el-row>

        <el-table :data="tableData.rows" border style="width: 100%" @selection-change="handleSelectionChange"
        :default-sort = "{prop: 'categoryName', order: 'ascending'}" @sort-change="customerSort"
        >
            <el-table-column type="expand">
                <template slot-scope="scope">
                  <el-form   label-width="100px">
                    <el-row style="padding: 10px;">
                      <el-col :span="24">
                        <el-form-item   label="创建时间" >
                            {{scope.row.createTime}}
                        </el-form-item>
                      </el-col>

                      <el-col :span="24">
                        <el-form-item   label="商品描述" >
                            <div v-html="scope.row.description"></div>
<!--                            {{scope.row.description}}-->
                        </el-form-item>
                      </el-col>

                      <el-col :span="24" v-if="scope.row.dishFlavors && scope.row.dishFlavors.length > 0">
                        <el-form-item   label="口味列表"  >
                            <div   class="flavorBox">

                              <!--商品本身有口味-->
                              <div   class="flavor">

                                <div v-for="(item ,index ) in scope.row.dishFlavors" class="cont">
                                  <!--口味名称 -->
                                  {{item.name}}

                                  <!-- 口味明细 -->
                                  <div class="labItems2">
                                   <!-- <el-tag v-for="(tag,ind) in item.value" :key="tag"   :disable-transitions="false" >
                                      {{ tag }}
                                    </el-tag> -->
                                    <DivItem v-for="(tag,ind) in item.value" :key="ind"  :value="tag.value" :money="tag.price"     >

                                     </DivItem>

                                  </div>

                                </div>

                              </div>
                            </div>
                        </el-form-item>
                      </el-col>

                    </el-row>
                    </el-form>
                </template>
              </el-table-column>
            <el-table-column type="selection" width="55" align="center" />
             <el-table-column prop="id" label="商品编号"  width="80"  />
             <el-table-column prop="merchantName" label="商家名称"   />
             <el-table-column prop="categoryName" label="商品分类"  sortable='custom' />
             <el-table-column prop="name" label="商品名称"   />
             <el-table-column prop="price" label="商品价格" sortable='custom'  />
             <el-table-column label="商品图片" width="220">
                 <template slot-scope="scope">
                     <img :src="scope.row.picture" width="150">
                 </template>
             </el-table-column>

             <el-table-column prop="isgrounding" label="上架状态" sortable='custom'>
               <template slot-scope="scope">
                  <DictTag :dataArray="dicts.shop_background" :value="scope.row.isgrounding"></DictTag>
               </template>
             </el-table-column>

            <el-table-column label="操作" align="center"  class-name="small-padding fixed-width">
                <template slot-scope="scope">
                    <el-button size="mini" type="text" icon="el-icon-edit"   v-shop @click="handleUpdate(scope.row)" >修改</el-button>
                    <el-button v-if="scope.row.isgrounding==='0'" size="mini" type="text" icon="el-icon-top" v-shop @click="handleUp(scope.row)">上架</el-button>
                    <el-button v-else class="btn-danger" size="mini" type="text" icon="el-icon-bottom"    v-shop @click="handleDown(scope.row)">下架</el-button>
                </template>
            </el-table-column>
        </el-table>


        <!-- 分页条 -->
        <el-pagination v-if="tableData.total>0" :current-page="queryParam.page" :page-sizes="[1, 5, 10, 20,30,50,100]"
                       :page-size="queryParam.size" layout="total, sizes, prev, pager, next, jumper" :total="tableData.total"
                       @size-change="handleSizeChange" @current-change="handleCurrentChange" />


        <!-- 新增和修改对话框-->
        <el-dialog :title="title" :visible.sync="open" width="1100px" append-to-body :close-on-click-modal="false" :before-close="cancelForm">
          <el-form ref="form" :model="form"   label-width="100px">
            <el-row>
              <el-col :span="12">
                <el-form-item label="菜品名称" prop="name" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
                  <el-input v-model="form.name" placeholder="请输入菜品名称" />
                </el-form-item>
              </el-col>

              <el-col :span="12">

                <el-form-item label="菜品分类" prop="categoryId" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
                  <el-select v-model="form.categoryId" placeholder="请选择">
                    <el-option
                      v-for="item in categoryList"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    />
                  </el-select>

                </el-form-item>
              </el-col>
            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="菜品价格" prop="price" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
                  <el-input v-model="form.price" placeholder="请输入菜品价格" />
                </el-form-item>
              </el-col>


              <el-col :span="12">
                <el-form-item label="状态" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">
                  <el-radio-group v-model="form.isgrounding">
                    <el-radio
                      v-for="dict in dicts.shop_background"
                      :key="dict.id"
                      :label="dict.dictValue"
                    >{{ dict.dictLabel }}</el-radio>
                  </el-radio-group>
                </el-form-item>
              </el-col>

            </el-row>

            <el-row>
              <el-col :span="12">
                <el-form-item label="库存" prop="num" :rules="[  { required: true, message: '该值不能为空', trigger: 'blur' }]">

                    <el-tooltip class="item" effect="dark" content="-1不限量" placement="right">
                        <el-input v-model="form.num" placeholder="-1不限量" />
                     </el-tooltip>
                </el-form-item>
              </el-col>


              <el-col :span="12">

              </el-col>

            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="口味配置">
                  <div v-if="form.dishFlavors" class="flavorBox">
                    <!-- 商品本身没有口味数据 -->
                    <el-button v-if="form.dishFlavors.length == 0" type="warning" class="addBut" @click="addFlavor()">+添加口味</el-button>

                    <!--商品本身有口味-->
                    <div v-if="form.dishFlavors.length != 0" class="flavor">

                      <div v-for="(item ,index ) in form.dishFlavors" class="cont">
                        <span>口味名（6个字内）</span>
                        <!--口味名称 -->
                        <el-autocomplete
                          v-model="item.name"
                          class="inline-input"
                          :fetch-suggestions="querySearch"
                          placeholder="请输入内容"
                          :maxlength="6"
                          show-word-limit
                          @select="handleSelect"
                        >
                          <template slot-scope="{ item }">
                            <span>{{ item }}</span>
                          </template>
                        </el-autocomplete>

                      <span class="delFlavor delBut non" @click="delFlavor(index)">删除</span>
                        <!-- 口味明细 -->

                        <div class="labItems">

                         <!-- <el-tag v-for="(tag,ind) in item.value" :key="ind" closable :disable-transitions="false" @close="handleClose(item,ind)">
                            {{ tag }}
                          </el-tag> -->
                          <el-tag effect="plain" class="labTag" v-for="(tag,ind) in item.value" :key="ind" closable :disable-transitions="false" @close="handleClose(item,ind)">
                              <ItemEdit    :item="tag"></ItemEdit>
                           </el-tag>


                          <el-button   class="button-new-tag" size="small" @click="showInput(item)">+ 添加</el-button>

                        </div>


                      </div>

                      <el-button type="warning" @click="addFlavor()">添加口味</el-button>

                    </div>
                  </div>

                </el-form-item>
              </el-col>

            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="菜品图片" prop="picture">
                  <el-upload
                    class="avatar-uploader"
                    :action="imageUploadUrl"
                    :show-file-list="false"
                    :headers="headers"
                    :on-success="handleAvatarSuccess"
                    :before-upload="beforeAvatarUpload"
                  >
                    <img v-if="form.picture" :src="form.picture" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon" />
                  </el-upload>
                  <div style="display:none;">
                    <el-input v-model="form.picture" style="width:0;height:0;" />
                  </div>
                </el-form-item>
              </el-col>

            </el-row>

            <el-row>
              <el-col :span="24">
                <el-form-item label="菜品描述">
                  <el-input
                    v-model="form.description"
                    type="textarea"
                    placeholder="请输入内容"
                  />
<!--                <QuillEditor @on-change="descriptChange" :value.sync="form.description" />-->
                </el-form-item>
              </el-col>
            </el-row>

          </el-form>

          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitForm">确 定</el-button>
            <el-button @click="cancelForm">取 消</el-button>
          </div>

        </el-dialog>


    </div>
</template>

<script>
    import PageMixin from '@/mixins/PageMixin.js'
    import AddOrEditMixin from '@/mixins/AddOrEditMixin.js'
    import DictMixin from '@/mixins/DictMixin.js'
    import {dataApi, addApi, editApi, findByIdApi, downloadExcel, upOrDownApi, dishFlavorApi } from '@/api/product.js'
    import {dataApi as categoryListApi} from '@/api/category.js'
    import DivItem from '@/components/DivItem/index.vue'
    import ItemEdit from '@/components/DivItem/edit.vue'

    //富文本框组件
    // import QuillEditor from '@/components/Editor/index.vue'
    export default {
        mixins: [DictMixin,PageMixin, AddOrEditMixin],
        dicts: ['shop_background'],
        components: {
          DivItem,
          ItemEdit
          // QuillEditor
        },
        data() {

            return {
                // 查询函数
                fetchDataApi: dataApi,
                // 新增函数
                addApi: addApi,
                // 新增函数
                editApi: editApi,
                // 新增函数
                findByIdApi: findByIdApi,
                primaryKey: 'id',
                //头像放到表单哪个字段里面
                uploadField: 'picture',
                // 商品分类
                categoryList: [],

            }
        },
        methods: {
          //当富文本框发生变化的时候，更改表单中的值
          descriptChange(obj){
            // obj={html:'网页的格式内容',  text:'文本内容', quill:富文本框对象}
            this.form.description = obj.html
          },

            // 重置表单
            initFormValue(){
              this.form = {
                picture: undefined,
                isgrounding: '0',
                num: -1,
                // 口味列表
                dishFlavors: [],
                description: undefined
              }
            },
            handleExcel(){
                this.download('/api/merchandise/download',this.queryParam,'merchandise_data.xlsx')
            },
            // 添加口味信息
            addFlavor() {
              if (this.form.dishFlavors.filter(p => p.name === '').length === 0) {
                this.form.dishFlavors.push({ name: '', value: [] })
              } else {
                this.$message.error('口味还没有配置完成，不能添加新口味')
              }
            },
            // 口味搜索建议  https://element.eleme.cn/#/zh-CN/component/input#dai-shu-ru-jian-yi
            querySearch(queryString, cb) {
              var arr = this.dicts.dish_flavor
              // 调用 callback 返回建议列表的数据
              var results = queryString ? arr.filter(p => p.name.startsWith(queryString)) : arr
              var mapValue = results.map(p => p.name)
              console.log(mapValue)
              cb(mapValue)
            },
            // 自动建议选中
            handleSelect(item) {
              // 判断是否在口味集合中 this.form.dishFlavors：[ {name:'',value:[],inputVisible:false,inputValue:''}]
              if (item) {
                var result = this.dicts.dish_flavor.filter(p => p.name === item)
                // 得到表单中最后一个口味对象
                var findObj = this.form.dishFlavors.filter(p => p.name === undefined || p.name === item)
                if (findObj.length > 1) {
                  this.$message.error('已经存在相同的口味名!')
                } else {
                  var obj = findObj[0]
                  obj.name = item
                  // 在里面
                  if (result.length > 0) {
                    //复制对象，深度copy
                    obj.value = this.deepCopy(result[0].value)
                  }
                }
              }
            },
            // 移出动态tags, 删除数组中的位置的值 item={name:'',value:[],inputVisible:false,inputValue:''}
            handleClose(item, index) {
              item.value.splice(index, 1)
            },
            // 点击动态添加tags
            showInput(item) {
              console.log(item.value)
              if (item.value.length >= 6) {
                this.$message.error('口味标签不能超过6个')
              } else {
                const data= {'value':'','price':0}
                item.value.push(data)
              }
            },

            // 根据下标删除form的口味
            delFlavor(index) {
              this.form.dishFlavors.splice(index, 1)
            },
            //读取所需要的数据信息
            initfetchList(){
              //用户的商品分类
              const params= {'page':1 , size: 1000}
              categoryListApi(params).then(resp=> {
                this.categoryList = resp.data.rows
              })
            },
            deepCopy(obj) {
              var a = JSON.stringify(obj)
              var newobj = JSON.parse(a)
              return newobj
           },
           //上架
           handleUp(row){
            let ids=[]
            ids.push(row[this.primaryKey])
            this.upOrDownProduct(ids,'1')
           },
           //下架
           handleDown(row){
             let ids=[]
             if(row) {
               ids.push(row[this.primaryKey])
             }else{
               ids=this.ids
             }
              this.upOrDownProduct(ids,'0')
           },
           upOrDownProduct(ids,status){
             this.$confirm('确定要进行此项操作吗?', '提示', {
               confirmButtonText: '确定',
               cancelButtonText: '取消',
               type: 'warning'
             }).then(() => {

              upOrDownApi(ids,status).then(resp => {
                 this.$message({ type: 'success', message: '操作成功!' })
                 // 重新查询数据
                 this.fetchData()
               })

             }).catch(() => {
             })
           },
           //自定义排序
           customerSort(column){
             console.log(column)
             //排序的列
             this.queryParam.sortBy= column.prop
             //排序的方式
              this.queryParam.order= column.order==='descending'?'desc' : 'asc'
             //重新发送请求
             this.handleQuery()
           },
        },


        created(){
            this.initFormValue()
            //读取所需要的数据信息,如果是管理员，则不需要读取
            if(this.$store.getters.accountType===2){
               this.initfetchList()
            }

            dishFlavorApi().then(resp=> {
              this.dicts.dish_flavor= resp.data
            })

        }

    }
</script>

<style scoped>
    .el-tag + .el-tag {
        margin-left: 10px;
      }
      .button-new-tag {
        margin-left: 10px;
        height: 32px;
        line-height: 30px;
        padding-top: 0;
        padding-bottom: 0;
      }
      .input-new-tag {
        width: 90px;
        margin-left: 10px;
        vertical-align: bottom;
      }

   .flavorBox .flavor {
     border: solid 1px #dfe2e8;
     border-radius: 3px;
     padding: 15px;
     background: #fafafb;
   }
   .flavorBox .flavor .title {
     color: #606168;
   }

   .flavor .el-autocomplete {
      width: 150px;
   }

   .flavorBox .flavor .cont .labItems {
     display: block;
     border-radius: 3px;
     border: solid 1px #d8dde3;
     background: #fff;
     padding: 0 5px;
     margin-left: 10px;
     margin-top: 10px;
   }

  .flavorBox .flavor .cont .labItems2 {
    border-radius: 3px;
    min-height: 39px;
    margin-left: 10px;
     background: #fff;
     line-height: 26px;
     padding-top: 3px;
  }

   .flavorBox .flavor .cont  .delFlavor {
     display: inline-block;
     padding: 0 10px;
     color: #f19c59;
     cursor: pointer;
     float: right;
   }

   .flavorBox .flavor .cont {
     margin: 10px 0;
     padding: 10px;
     background-color: #fff;
   }
   .flavorBox .title   .kwbq{
      margin-left: 45px;
   }

   .labTag{
     height: auto !important;
     margin-top: 10px;
   }

   .labItems .el-tag .el-icon-close{
     top: -50px;
   }

   .btn-danger{
     color:#f56c6c;
   }
</style>

<style>
  .labItems .el-tag .el-icon-close{
    top: -50px;
  }
</style>
